package cn.itsource.ymcc.mq;

import cn.itsource.ymcc.constant.ErrorConstantCode;
import cn.itsource.ymcc.constant.MQConstants;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.domain.PayOrder;
import cn.itsource.ymcc.service.ICourseOrderService;

import cn.itsource.ymcc.util.AssertUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@RocketMQMessageListener(
        consumerGroup = MQConstants.DELAY_ORDER_COMSUMER_GROUP,
        topic = MQConstants.DELAY_ORDER_NOTIFY_TOPIC,
        selectorExpression = "*",
        messageModel = MessageModel.BROADCASTING //多个消费者，广播

)
@Service
@Slf4j
public class DelayOrderLinster implements RocketMQListener<MessageExt> {

    @Autowired
    private ICourseOrderService courseOrderService;



    @Override
    public void onMessage(MessageExt messageExt) {
        log.info("orderserver 订单超时关闭");
        byte[] body = messageExt.getBody();
        String orderNo = new String(body, StandardCharsets.UTF_8);
        AssertUtil.isNotNull(orderNo, ErrorConstantCode.PARAMETER_NOT_BE_NULL);

        // 修改支付单状态，支付失败，订单关闭；
        Wrapper<CourseOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no",orderNo);
        CourseOrder courseOrder = courseOrderService.selectOne(wrapper);
        AssertUtil.isNotNull(courseOrder,ErrorConstantCode.PARAMETER_NOT_BE_NULL);

        // 超时取消！
        courseOrder.setUpdateTime(new Date());
        courseOrder.setStatusOrder(CourseOrder.CANCEL_PAY);

        log.info("更新订单状态！");
        courseOrderService.updateById(courseOrder);
    }
}
